package com.gao.d_selector.c;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Scanner;

// 	注意，该例子中，服务端是非阻塞的，而客户端是阻塞的
public class Client {
	public static void main(String[] args) {
		try {
			
			Scanner sc = new Scanner(System.in);
			
			SocketChannel socketChannel = SocketChannel.open();
			socketChannel.connect(new InetSocketAddress("127.0.0.1", 8000));
			
			ByteBuffer writeBuff = ByteBuffer.allocate(128);
			ByteBuffer readBuff = ByteBuffer.allocate(128);

			while(true) {

				System.out.println("请输入发送给地球的消息：");
				String msg = sc.nextLine();
				
				writeBuff.put(msg.getBytes());
				writeBuff.flip();
				
				writeBuff.rewind();
				socketChannel.write(writeBuff);
				writeBuff.clear();
				
				readBuff.clear();
				socketChannel.read(readBuff);
				
				System.out.println("client received: " + new String(readBuff.array()));
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
